package logic

import (
	"context"
	"errors"
	"goods/models/mysqlinit"
	"goods/models/redisinit"

	"goods/goods"
	"goods/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartCreateLogic {
	return &CartCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartCreateLogic) CartCreate(in *goods.CartCreateRequest) (*goods.CartCreateResponse, error) {
	// todo: add your logic here and delete this line
	g := mysqlinit.Goods{}
	err := g.FindGoods(int(in.GoodsId))
	if err != nil {
		logx.Error("获取商品失败")
		return nil, errors.New("获取商品失败")
	}
	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}
	if g.GoodsStock < int(in.Num) {
		logx.Error("商品库存不足")
		return nil, errors.New("商品库存不足")
	}
	if redisinit.Exists(in.UsersId, in.GoodsId) {
		err = redisinit.CartSub(in.UsersId, in.GoodsId, in.Num)
		if err != nil {
			logx.Error("购物车数量修改失败")
			return nil, errors.New("购物车数量修改失败")
		}
	} else {
		cart := map[string]interface{}{
			"UsersId":     in.UsersId,
			"GoodsId":     in.GoodsId,
			"Num":         in.Num,
			"GoodsTitle":  g.GoodsTitle,
			"GoodsPrice":  g.GoodsPrice,
			"GoodsStatus": g.GoodsStatus,
		}
		err = redisinit.CartCreate(cart)
		if err != nil {
			logx.Error("购物车添加失败")
			return nil, errors.New("购物车添加失败")
		}
	}
	return &goods.CartCreateResponse{
		Success: true,
	}, nil
}
